package com.boarsoft.flow.core.bean;

import java.util.Map;

import org.mvel2.MVEL;

import com.boarsoft.common.Util;

public class SwitchNode extends WrappedNode {
	/** 必需项 */
	protected Map<Object, String> branches;
	/** handler与expression二者必有其一 */
	protected SwitchHandler handler;
	/** handler与expression二者必有其一 */
	protected String expression;

	public int getType() {
		return BaseNode.TYPE_SWITCH;
	}

	public String getNext(Object data, Throwable throwable) throws Exception {
		if (handler != null) {
			Object v = handler.judge(data, throwable);
			if (branches.containsKey(v)) {
				return branches.get(v);
			}
			return this.getDefault();
		}
		if (Util.strIsNotEmpty(expression)) {
			String v = MVEL.evalToString(expression, data);
			if (branches.containsKey(v)) {
				return branches.get(v);
			}
			return this.getDefault();
		}
		throw new IllegalStateException(id.concat(//
				" is invalid SWITCH node, need handler or expression"));
	}

	public String getDefault() {
		if (this.branches.containsKey("default")) {
			return this.branches.get("default");
		}
		throw new IllegalStateException(id.concat(//
				" is invalid SWITCH node, need config case default"));
	}

	public Map<Object, String> getBranches() {
		return branches;
	}

	public void setBranches(Map<Object, String> branches) {
		this.branches = branches;
	}

	public SwitchHandler getHandler() {
		return handler;
	}

	public void setHandler(SwitchHandler handler) {
		this.handler = handler;
	}

	public String getExpression() {
		return expression;
	}

	public void setExpression(String expression) {
		this.expression = expression;
	}
}
